<template>
  <div class="app-container">
    <div class="top-filter">
      <el-button type="primary" @click="handleAdd">添加用户</el-button>
      <el-select placeholder="请选择用户状态" :value="statusValue" @change="handleStatusChange">
        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"> </el-option>
      </el-select>
    </div>
    <el-table v-loading="listLoading" :data="list" element-loading-text="Loading" border fit highlight-current-row>
      <!-- <el-table-column align="center" label="用户ID" min-width="200" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          {{ scope.row.UserId }}
        </template>
      </el-table-column> -->
      <el-table-column label="姓名" min-width="80" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          {{ scope.row.userName }}
        </template>
      </el-table-column>
      <el-table-column label="手机号码" width="110" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.mobile }}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色" min-width="150" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ scope.row.roles | roleFilter }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" prop="created_at" label="创建时间" width="200">
        <template slot-scope="scope">
          <span>{{ scope.row.createdOn | timeFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="created_at" label="实名时间" width="200">
        <template slot-scope="scope">
          <span>{{ scope.row.verifiedOn | timeFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="账号状态" width="110" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.verified | statusFilter">{{ scope.row.verified ? '已实名' : '未实名' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="created_at" label="操作" width="200">
        <template slot-scope="scope">
          <el-popconfirm
            title="确定该员工已离职吗？"
            v-if="scope.row.verified"
            @confirm="handleResign(scope.row.openId)"
          >
            <el-button type="text" slot="reference" style="margin-right: 8px">离职</el-button>
          </el-popconfirm>
          <el-button size="mini" type="text" @click="handleVerify(scope.row.openId)" v-if="!scope.row.verified"
            >去实名</el-button
          >
          <el-button size="mini" type="text" @click="handleEdit(scope.row.openId, 'UPDATE')" v-if="!scope.row.verified"
            >编辑</el-button
          >
          <el-button size="mini" type="text" @click="handleVerifiedEdit(scope.row.openId)" v-if="scope.row.verified"
            >编辑</el-button
          >
          <!-- <el-button size="mini" type="text" @click="handleRoleEdit" v-if="scope.row.Verified">编辑角色</el-button> -->
          <!-- <el-button size="mini" type="text" @click="handleRemove(scope.row)">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      small
      v-if="showPager"
      layout="prev, pager, next"
      :total="totalCount"
      @current-change="handleCurrentChange"
      :current-page.sync="currentPage"
    />
    <el-dialog
      :title="formType === 'EDIT' ? '修改用户信息' : '添加新用户'"
      :visible.sync="showForm"
      :before-close="handleClose"
    >
      <edit-form
        @form-submit="handleSubmit"
        @form-hide="handleClose"
        :defaultFormData="formData"
        :loading="submitLoading"
      ></edit-form>
    </el-dialog>
  </div>
</template>

<script>
import { getList, updateStaff, removeStaff, verifyStaff } from '@common/api/staff';
import { STAFF_STATUS, STAFF_CREATE, STAFF_UPDATE } from '@common/consts/staff';
import { formatTime } from '@common/utils/time';
import { Message } from 'element-ui';
import EditForm from './components/editForm.vue';

export default {
  components: { EditForm },
  filters: {
    statusFilter(status) {
      // 账号状态
      return status ? 'success' : 'gray';
    },
    roleFilter(roles) {
      // 角色
      if (!roles?.length) return '--';
      return roles?.map(v => v.RoleName).join('；');
    },
    timeFilter(time) {
      if (time) return formatTime(time);
      return '--';
    },
  },

  data() {
    return {
      list: [],
      listLoading: true,
      limit: 10,
      Offset: 0,
      showPager: false,
      options: [{ label: '全部', value: 'ALL' }, ...STAFF_STATUS],
      filter: [],
      statusValue: '',
      currentPage: 1,
      totalCount: 0,

      showForm: false, // 是否显示表单弹窗
      formType: '', // 表单类型
      formData: {}, // 编辑/新增表单数据
      verifyPop: false, // 是否显示实名认证弹窗
      verifySrc: '', // 实名认证地址
      submitLoading: false, // 表单提交loading
    };
  },
  created() {
    this.fetchData();
    // createUser({
    //   userName: 'test-an',
    // });
  },
  methods: {
    fetchData(params = {}) {
      this.listLoading = true;
      return getList({
        Limit: this.limit,
        Offset: 0,
        ...params,
      })
        .then(response => {
          this.list = response.data.list;
          this.listLoading = false;
          this.totalCount = response.data.totalCount;
          this.showPager = response.data.totalCount >= this.limit; // 无需分页
        })
        .catch(() => {
          this.listLoading = false;
        });
    },
    handleCurrentChange(data) {
      this.listLoading = true;
      this.offset = (data - 1) * this.limit;
      this.currentPage = data;
      this.fetchData({
        Offset: this.offset,
        Limit: this.limit,
      });
    },
    handleStatusChange(val) {
      // const optItem = this.options.find(item => item.value === val);
      if (val === 'ALL') {
        this.filter = [];
      } else {
        this.filter = [
          {
            Key: 'Status',
            Values: [val],
          },
        ];
      }

      this.statusValue = val;
      this.currentPage = 1;
      this.fetchData({
        Filters: this.filter,
        Offset: 0,
        Limit: this.limit,
      });
    },

    async handleRemove(row) {
      console.log(row, 'row.....');
      const confirm = await this.$confirm('确定删除吗？删除不可恢复。', '删除提示');
      if (confirm) {
        const removeRes = await removeStaff({
          employees: [{ UserId: row.userId, OpenId: row.openId }],
        });

        if (removeRes?.code === 20000) {
          this.$message('删除成功');
        }
      }
    },
    // 添加员工
    handleAdd() {
      this.showForm = true;
      this.formType = 'NEW';
      this.formData = {};
    },
    // 离职
    async handleResign(openId) {
      const res = await updateStaff({
        OperatorType: 'RESIGN',
        ProxyOrganizationOperators: [
          {
            Id: openId,
          },
        ],
      });
      if (res.data.Status === 1) {
        Message({
          message: '操作成功',
          type: 'success',
          duration: 5 * 1000,
        });
        this.currentPage = 1;
        this.fetchData();
      } else {
        Message({
          message: '操作失败',
          type: 'error',
          duration: 5 * 1000,
        });
      }
    },
    // 角色编辑
    async handleRoleEdit() {
      this.$router.push({
        path: '/staff/roles',
      });
    },
    // 编辑弹窗
    async handleEdit(openId) {
      this.showForm = true;
      this.formType = 'EDIT';
      console.log(this.list, 'this.list====');
      const targetStaff = this.list.find(v => v.openId === openId);
      this.formData = { ...targetStaff };
    },
    // 提交
    async handleSubmit(formData) {
      const msgPrefix = this.formType === 'EDIT' ? '修改' : '添加';
      const formParam = formData;
      if (this.formType === 'EDIT') {
        formParam.Id = formData.openId;
      }

      console.log(formParam, 'formParam===');
      const res = await updateStaff({
        OperatorType: this.formType === 'EDIT' ? STAFF_UPDATE : STAFF_CREATE,
        ProxyOrganizationOperators: [formParam],
      });
      if (res.data.Status === 1) {
        // 成功
        Message({
          message: `${msgPrefix}员工成功`,
          type: 'success',
          duration: 5 * 1000,
        });
        if (this.formType === 'NEW') this.currentPage = 1;
        this.fetchData();
      } else {
        Message({
          message: `${msgPrefix}员工失败`,
          type: 'error',
          duration: 5 * 1000,
        });
      }
      this.showForm = false;
      this.formType = '';
    },
    handleClose() {
      this.showForm = false;
      this.formType = '';
    },
    // 实名用户编辑
    async handleVerifiedEdit(openId) {
      const targetStaff = this.list.find(v => v.openId === openId);
      const res = await verifyStaff({
        user: targetStaff,
      });
      if (!res.data.ProxyOperatorIsVerified) {
        // 已离职员工ProxyOperatorIsVerified为false，生成实名认证链接，重新认证；
        this.verifySrc = res.data.ConsoleUrl;
        this.verifyPop = true;
      } else {
        Message({
          message: '当前员工已完成实名认证，修改前请先操作离职',
          type: 'warning',
          duration: 5 * 1000,
        });
      }
    },
    //  去实名
    async handleVerify(openId) {
      const targetStaff = this.list.find(v => v.openId === openId);
      this.$store.dispatch('user/showVerifyPopup', targetStaff);
    },
    finishVerify() {
      this.verifyPop = false;
      this.fetchData();
    },
  },
};
</script>
<style scoped>
.top-filter {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
}
</style>
